#pragma once

#include<iostream>
using namespace std;

#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

#include<ctime>
#include<cassert>
#include<cstring>

#include<string>


#define PATH "./"
#define PROJ_ID 1234
#define SIZE 4096


#define Debug   0
#define Notice  1
#define Warning 2
#define Error   3

const char* mes[] = {
    "Debug",
    "Notice",
    "Warning",
    "Error"
};

ostream& Log(const char* mesg, int level)
{
    cout << "[" << mes[level]  << "]" << "| " << time(nullptr) << " | ::" << mesg << endl;
    return cout;
}

// 十进制转十六进制打印
string deToHex(int key)
{
    char buf[20];
    snprintf(buf, sizeof(buf), "0x%x", key);
    return buf;
}

#define FIFO_PATH "./fifo"

class fifoCD
{
public:
    fifoCD()
    {
        // 将权限掩码改为0
        umask(0);
        if(mkfifo(FIFO_PATH, 0666) == -1)
        {
            Log("mkfifo fail", Error);
            exit(5);
        }
        Log("mkfifo success", Debug);
    }

    ~fifoCD()
    {
        // 删除文件可以用unlink函数
        unlink(FIFO_PATH);
        Log("del fifo done", Debug);
    }
};

#define READ O_RDONLY
#define WRITE O_WRONLY

int OpenFifo(string path, int flags)
{
    int fd = open(path.c_str(), flags);
    assert(fd != -1);

    return fd;
}

void CloseFifo(int fd)
{
    int ret = close(fd);
    assert(ret != -1);
    (void)ret;
}

void SendSignal(int fd)
{
    uint32_t signal = 1;
    ssize_t ret = write(fd, &signal, sizeof(uint32_t));
    assert(ret == sizeof(uint32_t));
    Log("client send signal", Notice) << endl;
}

void getSignal(int fd)
{
    Log("server waiting signal", Notice) << endl;
    uint32_t signal;
    ssize_t ret = read(fd, &signal, sizeof(uint32_t));
    assert(ret == sizeof(uint32_t));
}